package com.koicarp.university.graduate.auth.service;

import com.koicarp.university.graduate.auth.annotation.OperLog;
import com.koicarp.university.graduate.auth.constant.ModuleNameEnum;
import com.koicarp.university.graduate.auth.constant.OperateLogTypeEnum;
import com.koicarp.university.graudate.common.dto.SysUserDto;
import com.koicarp.university.graduate.auth.manager.UserManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @auther liutao
 * @Date 2020-08-17 11:58:35
 */
@Service
public class UniversityUserDetailService implements UserDetailsService {

    @Autowired
    private UserManager userManager;

    @Override
    @OperLog(moduleName = ModuleNameEnum.UserManage,type = OperateLogTypeEnum.LOGIN,operDesc = "系统用户登录")
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUserDto sysUser=userManager.findByUserIdOrTel(s);
        if (sysUser!=null) {
            String permissions = userManager.findUserPermissions(s);
            boolean notLocked = false;
            if (StringUtils.equals("1", String.valueOf(sysUser.getStatus()))){
                notLocked = true;
            }
            UniversityAuthUser authUser=new UniversityAuthUser(sysUser.getUserId(),sysUser.getPassword(), true,true,true,notLocked,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
            BeanUtils.copyProperties(sysUser,authUser);

            return authUser;
        }else{
            throw new UsernameNotFoundException("用户未找到");
        }
    }
}
